<template>
	<gui-page ref="guiPage" :customHeader="true">
		<!-- 导航 -->
		<template v-slot:gHeader>
			<nav-bar-custom left-icon="left" :title="$t('Common.IOTScanning')" @clickLeftBack="clickLeftBack"
				@clickRight="clickRight" scanType="0"></nav-bar-custom>
		</template>

		<template v-slot:gBody>
			<view class="barcodeSplitting">
				<!-- 扫描条码部分 -->
				<view class="gui-bg-white gui-dark-bg-level-3 gui-padding-x distributed-head">
					<view class="custom-card-title">
						<text class="title-line"></text>
						{{ $t('Common.scanningInfo') }}
					</view>
					<view class="custom-card-itemTwo" style="padding: 10rpx 0;">
						<text class="item-info-title"><text class="required-color">*</text>{{ $t('mexico.scanType')
						}}：</text>
						<view class="gui-form-body gui-text-right" style="overflow: visible;">
							<superweiCombox style="text-align: right;" :candidates="data.selectList"
								:placeholder="$t('distributedEnter.placeholderTextChoose')" :isJSON="true"
								keyName="name" @select="selectTypeClick" v-model="data.scanType">
							</superweiCombox>
						</view>
					</view>


					<!--选择AGV标号自动给位置赋值-->
					<view class="custom-card-itemTwo" style="padding: 10rpx 0;"  v-if="data.scanType=='AGV扫码失败扫码'">
						<text class="item-info-title">{{ $t('mexico.agvNo')
						}}：</text>
						<view class="gui-form-body gui-text-right" style="overflow: visible;">
							<superweiCombox style="text-align: right;" :candidates="data.agvList"
								:placeholder="$t('distributedEnter.placeholderTextChoose')" :isJSON="true"
								keyName="name" v-model="data.agvNo" @select="selectAgvNoClick">
							</superweiCombox>
						</view>
					</view>


					<view class="custom-card-itemTwo" style="padding: 10rpx 0;">
						<text class="item-info-title"><text class="required-color">*</text>{{
							$t('translationImage.process') }}：</text>
						<comboGrid ref="comboGridRef" v-model="data.process" :requestParam="data.requestParam"
							requestUrl="/api1/iot/open/GetProcessData"
							:placeholder="$t('distributedEnter.placeholderTextChoose')" inputKey="code"
							:column="data.columnRule.column" bindValue="locationName" @setClick="getRuleClick">
						</comboGrid>
					</view>
					<view class="custom-card-itemTwo" style="padding: 10rpx 0;">
						<text class="item-info-title"><text class="required-color">*</text>{{
							$t('multilingual.productionLine') }}：</text>
						<comboGrid ref="comboGridRef" v-model="data.productionLine" :requestParam="data.requestParam2"
							requestUrl="/api1/iot/open/GetProcessData"
							:placeholder="$t('distributedEnter.placeholderTextChoose')" inputKey="code"
							:column="data.columnRule2.column" bindValue="locationName" @setClick="getRuleClick2">
						</comboGrid>
					</view>
					<view class="custom-card-itemTwo" style="padding: 10rpx 0;">
						<text class="item-info-title"><text class="required-color">*</text>{{ $t('mexico.position')
						}}：</text>
						<comboGrid ref="comboGridRef" v-model="data.position" :requestParam="data.requestParam3"
							requestUrl="/api1/iot/open/GetProcessData"
							:placeholder="$t('distributedEnter.placeholderTextChoose')" inputKey="code"
							:column="data.columnRule3.column" bindValue="locationName" @setClick="getRuleClick3">
						</comboGrid>
					</view>
					<view class="gui-form-item gui-border-b" style="padding: 20rpx 0;">
						<text class="item-info-title" style="padding-right: 40rpx;">
							<text class="required-color">*</text>
							{{ $t('Common.barCode') }}
						</text>
						<uni-easyinput class="uni-mt-5" suffixIcon="scan" v-model="data.barCode" type="search"
							:placeholder="$t('Common.scanningBarCode')" @confirm="confirm" @iconClick="iconClick">
						</uni-easyinput>
					</view>
				</view>

				<!-- 提示信息 -->
				<view class="gui-flex gui-rows gui-nowrap gui-align-items-center gui-margin-top">
					<view class="gui-title-line"></view>
					<text class="gui-primary-text gui-h6" style="padding-left:50rpx; padding-right:50rpx;">{{
						$t('hardwareOut.barcodeInformation')
						}}</text>
					<view class="gui-title-line"></view>
				</view>

				<!-- 条码展示部分 -->
				<scroll-view :show-scrollbar="false" :scroll-y="true" class="scroll">
					<view style="height: 15rpx"></view>
					<view class="card-boxCustom" v-if="data.cardShow">
						<view class="card-body">
							<view class="custom-card-title">
								<text class="title-line"></text>
								{{ $t('distributedOut.atPresent') }}
							</view>
							<view class="custom-card-itemOne">
								<text class="body-item-title">{{ $t('distributedEnter.barcode')
								}}：</text>{{ data.scanInfo.barCode }}
							</view>
							<view class="custom-card-itemOne">
								<text class="body-item-title">{{ $t('mexico.scanType') }}：</text>
								{{ data.scanInfo.type }}
							</view>
							<view class="custom-card-itemOne">
								<text class="body-item-title">{{ $t('translationImage.process') }}：</text>
								{{ data.scanInfo.process }}
							</view>
							<view class="custom-card-itemOne">
								<text class="body-item-title">{{ $t('multilingual.productionLine') }}：</text>
								{{ data.scanInfo.productionLine }}
							</view>
							<view class="custom-card-itemOne">
								<text class="body-item-title">{{ $t('mexico.position') }}：</text>
								{{ data.scanInfo.position }}
							</view>

						</view>
					</view>
				</scroll-view>

				<!-- 底部确定按钮 -->
				<view class="page-bottom-box bottom-postion">
					<view class="page-bottomBtn bottomBtn-bgcolor-green" @click="submit">{{ $t('calendar.submit') }}
					</view>
				</view>


				<!-- 弹框填写数量 -->
				<uni-popup ref="inputDialog" type="center">
					<view class="input-dialog-box">
						<view class="input-dialog-content">
							<view class="input-dialog-item">
								{{ $t('distributedEnter.barcode') }}：{{ data.scanInfo.barCode }}
							</view>
							<view class="input-dialog-item">
								{{ $t('Common.pointPositionName') }}:{{ data.scanInfo.code }}
							</view>
							<view class="input-dialog-item"
								style="font-size: 18px;font-weight: 600;color: red; padding:20rpx 40rpx">
								{{ $t('slottedAsh.confirmWhether') }}
							</view>
						</view>
						<view class="input-dialog-footer">
							<view class="input-dialog-button" @click="cancelFn">
								{{ $t('popup.cancel') }}
							</view>
							<view class="input-dialog-button dialog-button-left" @click="confirmFn">
								{{ $t('popup.confirm') }}
							</view>
						</view>
					</view>
				</uni-popup>
			</view>
		</template>
	</gui-page>
</template>

<script setup>
//引入文件
import {
	ref,
	reactive,
	onMounted,
	computed,
	watch,
	toRaw
} from "vue";
import {
	iotScan,
	updateD,
	getAgvTaskProcessLineLocation
} from '@/api/api.js'
import pdaScan from '@/hooks/pdaScan.js'
import comboGrid from "@/components/comboGrid";
import superweiCombox from '@/components/superweiCombox';
import {
	onBackPress
} from '@dcloudio/uni-app';
import {
	useStore
} from "vuex";
import {
	basPdaOperationLogFn
} from '@/utils/index.js';
import {
	OPERATION_COMMIT,
	OPERATION_SCAN
} from '@/constant/index.js'
import {
	DEFAULT_WAREHOUSECODE,
	DEFAULT_WAREHOUSENAME,
	DEFAULT_WAREHOUSEID,
	BIGBARCODER_PRINT
} from '@/constant/index.js'
import {
	onShow
} from '@dcloudio/uni-app';

//JS国际化引入
import {
	useI18n
} from 'vue-i18n';
//注册组件
components: {
	comboGrid,
		superweiCombox
}

const {
	t
} = useI18n();

let store = useStore();
const {
	scan
} = pdaScan();

//页面弹框输入数量使用的变量
let inputDialog = ref(null);

	const data = reactive({
		selectList: [{
				name: t('人工上空托盘扫码'),
				id: '人工上空托盘扫码'
			},
			{
					name: t('投料扫码'),
					id: '投料扫码'
				},
			{
				name: t('mexico.LVTscanType'),
				id: '上基材上料扫码'
			}, {
				name: t('mexico.THscanType'),
				id: '贴合空托盘扫码'
			}, {
				name: t('mexico.DRscanType'),
				id: '打包扫码'
			}, {
				name: t('mexico.otherscanType'),
				id: 'AGV扫码失败扫码'
			}
		], //扫码类型



		//agv 类型
		agvList: [{
				name: 'L01',
				id: 'L01'
			},
			{
				name: 'L02',
				id: 'L02'
			}, {
				name: 'L03',
				id: 'L03'
			}, {
				name: 'L04',
				id: 'L04'
			}, {
				name: 'L05',
				id: 'L05'
			},
			{
				name: 'L06',
				id: 'L06'
			}, {
				name: 'L07',
				id: 'L07'
			}, {
				name: 'L08',
				id: 'L08'
			}, {
				name: 'L09',
				id: 'L09'
			},
			{
				name: 'M10',
				id: 'M10'
			}, {
				name: 'M11',
				id: 'M11'
			}, {
				name: 'M12',
				id: 'M12'
			}, {
				name: 'M13',
				id: 'M13'
			},
			{
				name: 'M14',
				id: 'M14'
			},
		],

		processLineLocation:{}, //工序，位置，产线信息

		scanType: '',
		scanTypeId: '',
		pointPosition: '', // 点位
		pointName: '',
		barCode: '', // 条码
		requestParam: {
			type: '1',
			parentCode: '',
			scanType: ''
		},
		requestParam2: {
			type: '2',
			parentCode: '',
			scanType: ''
		},
		requestParam3: {
			type: '3',
			parentCode: '',
			scanType: '',
			ProcessCode: ''
		},
		columnRule: {
			column: [{
				label: t('translationImage.process'),
				name: "text",
			}, {
				label: 'code',
				name: "code",
			}]
		},
		columnRule2: {
			column: [{
				label: t('newTranslation.productionLineCode'),
				name: "text",
			}, {
				label: t('newTranslation.productionLineName'),
				name: "code",
			}]
		},
		columnRule3: {
			column: [{
				label: t('Common.pointPositionCode'),
				name: "text",
			}, {
				label: t('Common.pointPositionName'),
				name: "code",
			}]
		},
		process: '', //工序
		processName: '', //点位名称
		productionLine: '', //产线
		productionLineName: '', //产线名称
		position: '', // 点位
		positionName: '', //点位名称
		scanInfo: {}, //当前扫描数组
		agvNo:'', //当前选择的AGV编号
		inventoryParam: {
			typeCode: 'BarcodeScannerConfig',
			warehouseCode: uni.getStorageSync(DEFAULT_WAREHOUSECODE) || '',
			code: ''
		},
		cardShow: false,
		id: null
	})

onShow(async () => {
	getRequestData()
	//refresh()
})
//
onMounted(() => {
	uni.$on('scancodedate', (data) => {
		console.log('获取到的code：' + data.code)
		getCode(data.code, 'pda')
	})
})

//仓库设置默认值
const getRequestData = () => {
	console.log(uni.getStorageSync(DEFAULT_WAREHOUSECODE))
	if (uni.getStorageSync(DEFAULT_WAREHOUSECODE) == '') {
		alertDialogOpen()
		return
	} else {
		data.warehouseCode = uni.getStorageSync(DEFAULT_WAREHOUSECODE) || '';
		data.warehouseName = uni.getStorageSync(DEFAULT_WAREHOUSENAME) || '';
		data.locationWarehouseId = uni.getStorageSync(DEFAULT_WAREHOUSEID) || '';
		data.inventoryParam.warehouseCode = uni.getStorageSync(DEFAULT_WAREHOUSECODE) || '';
	}
	// console.log(data.warehouseCode,data.warehouseName,data.locationWarehouseId)
}

const alertDialogOpen = () => {
	uni.showModal({
		content: t('pageTranslation.noDefaultLocation'),
		showCancel: false,
		title: t('smashRemoval.warmPrompt'),
		confirmText: t('pageTranslation.toSet'),
		success: function (res) {
			if (res.confirm) {
				uni.navigateTo({
					url: '/pages/setting/warehouse'
				})
			} else if (res.cancel) {

			}
		}
	});

}

// 扫描条码类型选择
const selectTypeClick = (e) => {
	data.scanTypeId = e.id
	data.requestParam.scanType = e.id
	data.requestParam2.scanType = e.id
	data.requestParam3.scanType = e.id
}




// Agv编号选择
const selectAgvNoClick = (e) => {
	getAgvTaskProcessLineLocation(e.id).then(res => {

		data.process = ''
		data.processName = ''
		data.productionLine = ''
		data.productionLineName = ''
		data.position = ''
		data.positionName = ''

		if (res.code == 200) {
			data.processLineLocation = res.result
			if (data.processLineLocation != null && data.processLineLocation.processCode != '') {
				data.process = data.processLineLocation.processCode
				data.processName = data.processLineLocation.processName

				data.productionLine = data.processLineLocation.lineCode
				data.productionLineName = data.processLineLocation.lineName


				data.position = data.processLineLocation.locationCode

				data.positionName = data.processLineLocation.locationName


				data.requestParam2.parentCode = data.processLineLocation.processCode

				data.requestParam3.parentCode = data.processLineLocation.lineCode
				data.requestParam3.ProcessCode = data.processLineLocation.processCode

			}
		}

	})
}





// 工序选择
const getRuleClick = (e) => {

	if (data.agvNo == "" && data.scanType == 'AGV扫码失败扫码') {

		uni.showToast({
			title: '请选择报警AGV编号',
			icon: 'error',
			duration: 2000,

		})
		return
	}

	data.productionLine = ''
	data.productionLineName = ''
	data.position = ''
	data.positionName = ''
	data.process = e.code
	data.processName = e.text
	data.requestParam2.parentCode = e.code
}

// 产线选择
const getRuleClick2 = (e) => {


	data.position = ''
	data.positionName = ''
	data.productionLine = e.code
	data.requestParam3.parentCode = e.code
	data.requestParam3.ProcessCode = data.process
	data.productionLineName = e.text
}
// 位置选择
const getRuleClick3 = (e) => {
	data.position = e.code
	data.positionName = e.text
}

// 计算监听扫描
data.scanList = computed(() => {
	console.log(store.state.iotScanning, 'data.scanList')
	return store.state.iotScanning
})
// 扫描条码事件
const confirm = () => {
	getCode(data.barCode, 'keydown')
}
// 监听用户使用相机
const iconClick = async (type) => {
	if (type === 'suffix') {
		let code = await scan();
		getCode(code, 'scan')
	}
}
const getCode = (code, type) => {
	// 存储扫描的的条码,通过barode去判断是否有重复
	let arr = data.scanList.filter(x => x.barcode == code);
	if (arr.length > 0) {
		uni.showToast({
			title: t('smashRemoval.codesRepeatedly'),
			icon: 'none'
		});
		return
	}
	// 其他判断条件 扫描类型  工序 产线  点位
	if (!data.scanType) {
		uni.showToast({
			title: t('mexico.scanTypePlease'),
			icon: 'none'
		});
		return
	}

	if ((!code.startsWith('T')) && (!code.startsWith('M'))) {
		uni.showToast({
			title: t('mexico.scanTypeStart'),
			icon: 'none'
		});
		return
	}
	data.barCode = code
	let str = {
		barCode: data.barCode,
		type: data.scanType,
		process: data.process,
		productionLine: data.productionLine,
		position: data.position,

	}
	uni.showToast({
		title: t('mexico.scanningSuccessful'),
		icon: 'none'
	});
	data.scanInfo = str
	data.cardShow = true
	// store.commit('addIotScanningList',data.scanInfo)
}


// 提交事件
const submit = () => {
	if (!data.process) {
		uni.showToast({
			title: t('JsInternational.chooseLine'),
			icon: "none"
		});
		return
	}
	if (!data.productionLine) {
		uni.showToast({
			title: t('JsInternational.chooseOperation'),
			icon: "none"
		});
		return
	}
	if (!data.position) {
		uni.showToast({
			title: t('taskList.selectLocation'),
			icon: "none"
		});
		return
	}
	if (!data.barCode) {
		uni.showToast({
			title: t('stockManage.pleaseScanCode'),
			icon: "none"
		});
		return
	}

	uni.showLoading({
		title: 'loading',
		mask: true
	});
	iotScan({
		processCode: data.process,
		locationCode: data.position,
		lineCode: data.productionLine,
		scanCode: data.barCode,
		scanType: data.scanTypeId   // 扫描条码类型
	}).then(res => {
		try {
			let inputParameter = JSON.stringify(data.scanInfo)
			let returnParameter = JSON.stringify(res)
			let operationPicture = 'IOT扫描'
			let callInterface = res.rquestUrl
			let opertionParmes = {
				inputParameter,
				returnParameter,
				operationPicture,
				callInterface,
				responseCode: res.status, //返回状态
				errorMessage: res.message, //错误信息
				isPass: res.statusCode == 200 ? 'Y' : 'N', //是否成功 Y N
				operationType: OPERATION_COMMIT
			}
			basPdaOperationLogFn(opertionParmes)
		} catch (error) { }
		if (res.code == 200) {
			//隐藏加载框
			uni.hideLoading();
			data.scanInfo = {}
			data.barCode = ''
			data.process = ''
			data.productionLine = ''
			data.position = ''
			data.scanType = ''
			uni.showToast({
				title: '提交成功'
			});
			// inputDialog.value.close();

		} else {
			uni.hideLoading();
			uni.showToast({
				title: res.message
			})
		}
	})
	//打开弹框
	// inputDialog.value.open();
}

const confirmFn = () => {
	// 添加加载框
	uni.showLoading({
		title: 'loading',
		mask: true
	});
	updateD({
		code: data.scanInfo.code,
		value: data.scanInfo.value,
		text: data.scanInfo.text,
		sequence: data.scanInfo.sequence,
		typeCode: data.scanInfo.typeCode,
		remark: data.scanInfo.remark,
		hid: Number(data.scanInfo.id),
	}).then(res => {
		try {
			let inputParameter = JSON.stringify(data.scanInfo)
			let returnParameter = JSON.stringify(res)
			let operationPicture = 'IOT扫描提交'
			let callInterface = res.rquestUrl
			let opertionParmes = {
				inputParameter,
				returnParameter,
				operationPicture,
				callInterface,
				responseCode: res.status, //返回状态
				errorMessage: res.message, //错误信息
				isPass: res.statusCode == 200 ? 'Y' : 'N', //是否成功 Y N
				operationType: OPERATION_COMMIT
			}
			basPdaOperationLogFn(opertionParmes)
		} catch (error) { }
		if (res.statusCode == 200) {
			//隐藏加载框
			uni.hideLoading();
			data.scanInfo = {}
			data.barCode = ''
			uni.showToast({
				title: res.message
			});
			inputDialog.value.close();

		} else {
			uni.hideLoading();
			//uni.showToast({ title: res.message });
			uni.showModal({
				content: res.message,
				showCancel: false
			})
		}
	})
}


// 扫描纪录
const clickRight = () => {
	navigate({
		url: '/pages/IOTScanning/IOTScanningRecord'
	})
}


//导航栏左侧返回
const clickLeftBack = () => {
	navBackCheck()
}
const navBackCheck = () => {
	if (!data.scanList.length) {
		uni.navigateBack({
			delta: 1
		});
		return true
	}
	uni.showModal({
		title: t('smashRemoval.warmPrompt'),
		content: t('materials.unsubmittedDataIn'),
		success: function (res) {
			if (res.confirm) {
				store.commit('clearIotScanningList') // 清空条码数据
				console.log(data.scanList);
				uni.navigateBack({
					delta: 1
				});
			} else if (res.cancel) {
				console.log('用户点击取消');
			}
		}
	});
}
//点击物理按键的返回
onBackPress((options) => {
	if (options.from == 'backbutton') {
		if (!data.scanList.length) {
			uni.navigateBack({
				delta: 1
			});
			return true
		}
		uni.showModal({
			title: t('smashRemoval.warmPrompt'),
			content: t('materials.unsubmittedDataIn'),
			success: function (res) {
				if (res.confirm) {
					//清除store 里面的数据
					store.commit("clearIotScanningList");
					console.log(data.scanList);
					uni.navigateBack({
						delta: 1
					});
				} else if (res.cancel) {
					console.log('用户点击取消');
				}
			}
		});
		return true;
	}
})

const refresh = () => {
	uni.redirectTo({
		url: '/pages/IOTScanning/IOTScanning'
	});
}

// 弹框的取消按钮
const cancelFn = () => {
	inputDialog.value.close();
}
</script>

<style lang="scss" scoped>
.barcodeSplitting {
	display: flex;
	flex-direction: column;
	height: calc(100vh - 88rpx);
	// height: 100vh;
}

.distributed-head {
	border-bottom-left-radius: 16rpx;
	border-bottom-right-radius: 16rpx;
}

.scroll {
	flex: 1;
	height: 2rpx;
}
</style>
